package com.bidding.auth.config;

import cn.dev33.satoken.stp.StpInterface;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.bidding.auth.pojo.entity.AuthPermission;
import com.bidding.auth.pojo.entity.AuthRole;
import com.bidding.common.utils.RedisUtil;
import com.google.gson.Gson;

import com.google.gson.reflect.TypeToken;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 自定义权限验证接口扩展 
 */
@Component
public class StpInterfaceImpl implements StpInterface {

    @Resource
    private RedisUtil redisUtil;

    private final String authPermissionPrefix = "auth.permission";
    private final String authRolePrefix = "auth.role";

    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        String authKey = redisUtil.buildKey(authPermissionPrefix, loginId.toString());
        String authValue = redisUtil.get(authKey);
        if (StringUtils.isBlank(authValue)){
            return Collections.emptyList();
        }
        List<AuthPermission> permissionList = new Gson().fromJson(authValue, new TypeToken<List<AuthPermission>>(){}.getType());

        return permissionList.stream().map(AuthPermission::getPermissionKey).collect(Collectors.toList());
    }

    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        String authKey = redisUtil.buildKey(authRolePrefix, loginId.toString());
        String authValue = redisUtil.get(authKey);
        if (StringUtils.isBlank(authValue)){
            return Collections.emptyList();
        }
        List<AuthRole> authRoleList = new Gson().fromJson(authValue, new TypeToken<List<AuthRole>>(){}.getType());

        return authRoleList.stream().map(AuthRole::getRoleKey).collect(Collectors.toList());
    }

}
